<?php

error_reporting (E_ALL ^ E_NOTICE);

include('cfg/def.php');
include('cfg/cfg.php');

include_once('lib/utils.class.php');
include_once('lib/timer.class.php');
include_once('lib/xtemplate.class.php');

include_once('views/views.class.php');

$timer = new Timer('page', TRUE, Timer::FORMAT_S);

include_once('lib/logger.class.php');
Logger::$log_file = $log_file_ajax;

include_once('models/user.class.php');
include_once('models/parser.class.php');

session_start();
header('Cache-Control: no-cache');
if(0 || empty($_SESSION["AJAXABLE"]) || $_SESSION["AJAXABLE"] != "YES")
{
	header('Content-Type: text/plain; charset=utf-8');
	echo "Неверный формат запроса";
	exit(0);
}

Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "POST: ".print_r($_POST, true));
Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "GET: ".print_r($_GET, true));

// убираем случайный мусор вначале и в конце
foreach($_POST as $key=>$val) $_POST[$key] = trim($val);
foreach($_GET as $key=>$val) $_GET[$key] = trim($val);

// Пакет ответа
$pack_a = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><pack />');
// Посетитель
$u = new User();
// Авторизация
if($u->auth())
{
	header('Content-Type: text/plain; charset=utf-8');
	$page = Utils::get_param('page', null);
	$cmd = Utils::get_param('cmd', null);
	$type = Utils::get_param('type', null);
	$ans = arr2json(array());
	if($page)
	{
		switch($page)
		{
			case 'act':
				switch($cmd)
				{
					case 'clear':
						$u->clear_log();
						$ans = json_encode("OK");
						break;
					
					case 'dir':
						$dir = $_REQUEST['dir'];
						$files = scandir($dir);
						$data = array();
						foreach($files as $file)
						{
							if(is_dir($file)) continue;
							array_push($data, $file);
						}
						$ans = json_encode($data);
						break;
					
					case 'run':
						if(true)
						{
							$parser = new Parser();
							$file = $_REQUEST['file'];
							$letter = file_get_contents($file);

							$parser->load_data();
							$sms = $parser->parse_letter($letter);
							if($sms)
								$ans = json_encode("OK of ".$file);
							else
								$ans = json_encode("ERROR of ".$file);
							
							/*
							$comp = $parser->get_company_props($letter);
							if($comp !== false)
							{
								$id_list = $parser->get_identificators($letter, $comp);
								$cli_list = $parser->get_clients($id_list, $comp);
								foreach($cli_list as $cli)
								{
									$sms = $parser->get_sms($letter, $comp);
								}
								$ans = json_encode("OK of ".$file);
							}
							else
							{
								$ans = json_encode("ERROR of ".$file);
							}
							*/
						}
						else
						{
							$ans = json_encode("OK");
						}
						break;
				}
				break;
			
			case 'msg':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_messages();
						$ans = arr2json($data);
						break;
					
					case 'msg':
						$msg_id = Utils::get_param('id', null);
						$data = $u->load_message_details($msg_id);
						$ans = json_encode($data);
						break;
				}
				break;
		
			case 'cli':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_clients();
						$ans = arr2json($data);
						break;
					
					case 'upd':
						$u->update_client();
						$ans = $_POST['value'];
						break;
					
					case 'ins':
						$ans = $u->insert_client();
						break;
					
					case 'del':
						$ans = $u->delete_client();
						break;
				}
				break;
			
			case 'cmp':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_companies();
						$ans = arr2json($data);
						break;
					
					case 'upd':
						$u->update_company();
						$ans = $_POST['value'];
						break;
					
					case 'ins':
						$ans = $u->insert_company();
						break;
					
					case 'del':
						$ans = $u->delete_company();
						break;
					
					case 'list':
						$data = $u->get_company_list();
						$ans = json_encode($data);
						break;
				}
				break;
			
			case 'usr':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_users();
						$ans = arr2json($data);
						break;
					
					case 'upd':
						$u->update_user();
						$ans = $_POST['value'];
						break;
					
					case 'ins':
						$ans = $u->insert_user();
						break;
					
					case 'del':
						$ans = $u->delete_user();
						break;
				}
				break;
			
			case 'set':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_settings($type);
						$ans = arr2json($data);
						break;
					
					case 'upd':
						$u->update_settings();
						$ans = $_POST['value'];
						break;
					
					case 'ins':
						$ans = $u->insert_settings();
						break;
					
					case 'del':
						$ans = $u->delete_settings();
						break;
				}
				break;
			
			case 'tpl':
				switch($cmd)
				{
					case 'sel':
						$data = $u->load_templates();
						$ans = arr2json($data);
						break;
					
					case 'upd':
						$u->update_template();
						$ans = $_POST['value'];
						break;
					
					case 'ins':
						$ans = $u->insert_template();
						break;
					
					case 'del':
						$ans = $u->delete_template();
						break;
				}
				break;
			
			case 'prf':
				Logger::Write(__FILE__." line ".__LINE__, 'PRF');
				switch($cmd)
				{
					case 'chg':
						Logger::Write(__FILE__." line ".__LINE__, 'CHG');
						$ans = $u->change_password($_REQUEST['op'], $_REQUEST['np'], $_REQUEST['rp']);
						break;
				}
				break;
		}
		echo $ans;
		// Logger::Write(__FILE__." line ".__LINE__, 'DB DATA: '.print_r($data, true));
		// Logger::Write(__FILE__." line ".__LINE__, 'AJAX ANSWER: '.$ans);
		exit();
	}
	
}
else
{
	Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "no authorization");
	header('Content-Type: text/plain; charset=utf-8');
	echo 'Ошибка доступа';
	exit();
}

function arr2json($arr)
{
    $output = array(
        "sEcho" => Utils::get_param($_GET['_'], 1),
        "iTotalRecords" => count($arr),
        "iTotalDisplayRecords" => 25,
        "aaData" => $arr
    );

    return json_encode( $output );
}
